<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<style>
    .announcement-card {
        position: absolute;
        top: 100%;
        right: 0;
        width: 350px;
        max-height: 500px;
        background: white;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 1050;
        margin-top: 8px;
        overflow: hidden;
    }
    .announcement-card-header {
        padding: 12px 16px;
        border-bottom: 1px solid #dee2e6;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f8f9fa;
    }
    .announcement-card-body {
        max-height: 400px;
        overflow-y: auto;
        padding: 0;
    }
    .announcement-item {
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .announcement-item:hover {
        background-color: #f8f9fa;
    }
    .announcement-item:last-child {
        border-bottom: none;
    }
    .announcement-title {
        font-weight: 600;
        color: #212529;
        margin-bottom: 4px;
        font-size: 14px;
    }
    .announcement-content {
        color: #6c757d;
        font-size: 12px;
        margin-bottom: 4px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .announcement-time {
        color: #adb5bd;
        font-size: 11px;
    }
    .announcement-empty {
        padding: 40px 20px;
        text-align: center;
        color: #6c757d;
    }
    #announcementIcon:hover {
        opacity: 0.8;
    }
    .navbar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1030;
        width: 100%;
    }
    body {
        padding-top: 56px;
    }
    /* AI咨询悬浮按钮 */
    .ai-consultation-float-btn {
        position: fixed;
        right: 20px;
        bottom: 20px;
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        cursor: pointer;
        z-index: 1000;
        transition: all 0.3s ease;
        text-decoration: none;
        color: white;
    }
    .ai-consultation-float-btn:hover {
        transform: scale(1.1);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
        color: white;
        text-decoration: none;
    }
    .ai-consultation-float-btn svg {
        width: 30px;
        height: 30px;
    }
</style>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/client/index">助农购物</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/client/index">首页</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/client/cart?action=list">
                        购物车
                        <c:if test="${sessionScope.user != null}">
                            <span class="badge bg-danger" id="cartCount" style="display: none;">0</span>
                        </c:if>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/client/order?action=list">订单管理</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/client/review?action=list">农产品评价</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/client/consultation">咨询商家</a>
                </li>
            </ul>
            <ul class="navbar-nav">
                <c:choose>
                    <c:when test="${sessionScope.user != null}">
                        <!-- 公告图标 -->
                        <li class="nav-item position-relative me-2 d-flex align-items-center" id="announcementContainer">
                            <a class="nav-link d-flex align-items-center" href="javascript:void(0)" id="announcementIcon" style="cursor: pointer;">
                                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16">
                                    <path d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 1.197-.448 1.742-.448.72-.973 1.135-1.552 1.135h-.448c-.179 0-.322.144-.322.323v.792c0 .18.143.323.322.323h11.112c.18 0 .322-.144.322-.323v-.792c0-.18-.143-.323-.322-.323h-.448c-.58 0-1.104-.415-1.552-1.135C12.134 7.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"/>
                                </svg>
                                <span class="badge bg-danger position-absolute top-0 start-100 translate-middle" id="announcementBadge" style="display: none; font-size: 0.6rem;">0</span>
                            </a>
                            <!-- 公告卡片 -->
                            <div class="announcement-card" id="announcementCard" style="display: none;">
                                <div class="announcement-card-header">
                                    <h6 class="mb-0">公告通知</h6>
                                    <button type="button" class="btn-close btn-close-sm" id="closeAnnouncementCard"></button>
                                </div>
                                <div class="announcement-card-body" id="announcementList">
                                    <div class="text-center text-muted py-3">
                                        <div class="spinner-border spinner-border-sm" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                        <div class="mt-2">加载中...</div>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <li class="nav-item dropdown d-flex align-items-center">
                            <a class="nav-link dropdown-toggle d-flex align-items-center" href="javascript:void(0)" id="userDropdown" role="button" 
                               data-bs-toggle="dropdown" aria-expanded="false" aria-haspopup="true" style="height: 100%;">
                                ${sessionScope.user.realName != null && !empty sessionScope.user.realName ? sessionScope.user.realName : sessionScope.user.username}
                            </a>
                            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                                <li><a class="dropdown-item" href="${pageContext.request.contextPath}/client/user?action=profile">个人中心</a></li>
                                <li><a class="dropdown-item" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#rechargeModal" onclick="event.stopPropagation();">充值</a></li>
                                <li><a class="dropdown-item" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#changePasswordModal" onclick="event.stopPropagation();">修改密码</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="${pageContext.request.contextPath}/logout">退出登录</a></li>
                            </ul>
                        </li>
                    </c:when>
                    <c:otherwise>
                        <li class="nav-item">
                            <a class="nav-link" href="${pageContext.request.contextPath}/login.jsp">登录</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="${pageContext.request.contextPath}/register.jsp">注册</a>
                        </li>
                    </c:otherwise>
                </c:choose>
            </ul>
        </div>
    </div>
</nav>

<!-- 充值模态框 -->
<div class="modal fade" id="rechargeModal" tabindex="-1" aria-labelledby="rechargeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rechargeModalLabel">账户充值</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">当前余额：<strong class="text-success">¥<fmt:formatNumber value="${sessionScope.user.balance != null ? sessionScope.user.balance : 0}" pattern="#,##0.00"/></strong></label>
                </div>
                <form id="rechargeForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label for="rechargeAmount" class="form-label">充值金额</label>
                        <input type="text" class="form-control" id="rechargeAmount" name="amount" 
                               placeholder="请输入充值金额（0.01-999999.99）" required
                               onkeydown="return handleRechargeKeydown(event)"
                               oninput="validateRechargeAmount(this)"
                               onblur="validateRechargeAmount(this)"
                               onpaste="handleRechargePaste(event)">
                        <div class="invalid-feedback" id="rechargeAmountError"></div>
                        <small class="form-text text-muted">单次充值金额范围：0.01 - 999,999.99 元（最多2位小数）</small>
                    </div>
                    <div class="alert alert-danger d-none" id="rechargeError"></div>
                    <div class="alert alert-success d-none" id="rechargeSuccess"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="rechargeSubmitBtn">确认充值</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel">修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm" onsubmit="return false;">
                    <div class="mb-3">
                        <label for="oldPassword" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="oldPassword" name="oldPassword" 
                               placeholder="请输入当前密码" required
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="oldPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" 
                               placeholder="请输入新密码（至少6位）" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="newPasswordError"></div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">确认密码</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" 
                               placeholder="请再次输入新密码" required minlength="6"
                               onkeydown="if(event.keyCode===13){event.preventDefault();return false;}">
                        <div class="invalid-feedback" id="confirmPasswordError"></div>
                    </div>
                    <div class="alert alert-danger d-none" id="changePasswordError"></div>
                    <div class="alert alert-success d-none" id="changePasswordSuccess"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="changePasswordSubmitBtn">确认修改</button>
            </div>
        </div>
    </div>
</div>

<script>
// 等待DOM和Bootstrap加载完成
(function() {
    // 确保Bootstrap下拉菜单初始化
    function initDropdowns() {
        // 等待Bootstrap加载
        if (typeof bootstrap === 'undefined' || !bootstrap.Dropdown) {
            setTimeout(initDropdowns, 50);
            return;
        }
        
        var dropdownElementList = document.querySelectorAll('.dropdown-toggle');
        dropdownElementList.forEach(function (dropdownToggleEl) {
            try {
                // 检查是否已经初始化
                var dropdownInstance = bootstrap.Dropdown.getInstance(dropdownToggleEl);
                if (!dropdownInstance) {
                    new bootstrap.Dropdown(dropdownToggleEl);
                }
            } catch (e) {
                console.error('初始化下拉菜单失败:', e);
            }
        });
    }
    
    // DOM加载完成后初始化
    function initAll() {
        initDropdowns();
        initModals();
    }
    
    // 等待页面加载完成和Bootstrap JS加载
    function waitForBootstrap() {
        if (typeof bootstrap !== 'undefined' && bootstrap.Dropdown) {
            initAll();
        } else {
            setTimeout(waitForBootstrap, 50);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', waitForBootstrap);
    } else {
        waitForBootstrap();
    }
    
    // 处理充值输入框按键事件，限制输入
    function handleRechargeKeydown(event) {
        // 允许的按键：数字0-9、小数点、退格、删除、Tab、方向键、Enter
        var allowedKeys = [8, 9, 13, 37, 38, 39, 40, 46]; // 退格、Tab、Enter、方向键、删除
        var keyCode = event.keyCode || event.which;
        var charCode = event.charCode || event.which;
        var char = String.fromCharCode(charCode);
        
        // 允许控制键
        if (allowedKeys.indexOf(keyCode) !== -1) {
            return true;
        }
        
        // 允许数字和小数点
        if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) {
            // 数字键
            var input = event.target;
            var value = input.value;
            
            // 如果已经有小数点，不能再输入小数点
            if (char === '.' && value.indexOf('.') !== -1) {
                event.preventDefault();
                return false;
            }
            
            // 检查小数位数
            if (value.indexOf('.') !== -1) {
                var decimalPart = value.split('.')[1];
                if (decimalPart && decimalPart.length >= 2) {
                    event.preventDefault();
                    return false;
                }
            }
            
            return true;
        }
        
        // 允许小数点
        if (char === '.' || keyCode === 190 || keyCode === 110) {
            var input = event.target;
            var value = input.value;
            // 如果已经有小数点，不能再输入
            if (value.indexOf('.') !== -1) {
                event.preventDefault();
                return false;
            }
            return true;
        }
        
        // 阻止Enter键提交表单
        if (keyCode === 13) {
            event.preventDefault();
            return false;
        }
        
        // 阻止其他字符
        event.preventDefault();
        return false;
    }
    
    // 处理粘贴事件，过滤非法字符
    function handleRechargePaste(event) {
        var input = event.target;
        setTimeout(function() {
            var value = input.value;
            // 只保留数字和小数点
            var cleaned = value.replace(/[^\d.]/g, '');
            // 只保留第一个小数点
            var parts = cleaned.split('.');
            if (parts.length > 2) {
                cleaned = parts[0] + '.' + parts.slice(1).join('');
            }
            // 限制小数位数
            if (cleaned.indexOf('.') !== -1) {
                var decimalPart = cleaned.split('.')[1];
                if (decimalPart && decimalPart.length > 2) {
                    cleaned = cleaned.substring(0, cleaned.indexOf('.') + 3);
                }
            }
            input.value = cleaned;
            validateRechargeAmount(input);
        }, 0);
    }
    
    // 充值金额校验函数
    function validateRechargeAmount(input) {
        var amountInput = input;
        var amount = amountInput.value;
        var errorMsg = document.getElementById('rechargeAmountError');
        var result = { isValid: true, message: '' };
        
        // 清除之前的错误状态
        amountInput.classList.remove('is-invalid');
        if (errorMsg) errorMsg.textContent = '';
        
        // 去除空格
        if (amount) {
            amount = amount.trim();
            amountInput.value = amount;
        }
        
        // 检查是否为空
        if (!amount || amount === '') {
            // 空值时不显示错误，只在提交时校验
            result.isValid = false;
            result.message = '请输入充值金额';
            return result;
        }
        
        // 验证格式：只允许数字和小数点，最多2位小数
        if (!amount.match(/^\d+(\.\d{1,2})?$/)) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '请输入有效的金额格式（最多2位小数）';
            result.isValid = false;
            result.message = '请输入有效的金额格式（最多2位小数）';
            return result;
        }
        
        // 检查是否为有效数字
        var amountValue = parseFloat(amount);
        if (isNaN(amountValue)) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '请输入有效的数字';
            result.isValid = false;
            result.message = '请输入有效的数字';
            return result;
        }
        
        // 检查是否大于0
        if (amountValue <= 0) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '充值金额必须大于0';
            result.isValid = false;
            result.message = '充值金额必须大于0';
            return result;
        }
        
        // 检查最小金额（0.01）
        if (amountValue < 0.01) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '充值金额不能少于0.01元';
            result.isValid = false;
            result.message = '充值金额不能少于0.01元';
            return result;
        }
        
        // 检查最大金额（999999.99）
        if (amountValue > 999999.99) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '单次充值金额不能超过999,999.99元';
            result.isValid = false;
            result.message = '单次充值金额不能超过999,999.99元';
            return result;
        }
        
        // 检查小数位数（最多2位）
        var decimalPart = amount.toString().split('.')[1];
        if (decimalPart && decimalPart.length > 2) {
            amountInput.classList.add('is-invalid');
            if (errorMsg) errorMsg.textContent = '金额最多保留2位小数';
            result.isValid = false;
            result.message = '金额最多保留2位小数';
            // 自动修正为2位小数
            amountInput.value = amountValue.toFixed(2);
            return result;
        }
        
        // 校验通过
        amountInput.classList.remove('is-invalid');
        amountInput.classList.add('is-valid');
        if (errorMsg) errorMsg.textContent = '';
        result.isValid = true;
        return result;
    }
    
    // 初始化模态框相关功能
    function initModals() {
        // 充值功能
        var rechargeBtn = document.getElementById('rechargeSubmitBtn');
        if (rechargeBtn) {
            rechargeBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                // 重新获取元素和值
                var amountInput = document.getElementById('rechargeAmount');
                if (!amountInput) {
                    console.error('找不到充值金额输入框');
                    return;
                }
                
                var amount = amountInput.value;
                if (amount) {
                    amount = amount.trim();
                }
                
                var errorDiv = document.getElementById('rechargeError');
                var successDiv = document.getElementById('rechargeSuccess');
                
                // 清除之前的消息
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                amountInput.classList.remove('is-invalid');
                amountInput.classList.remove('is-valid');
                
                // 验证金额
                var validationResult = validateRechargeAmount(amountInput);
                if (!validationResult.isValid) {
                    if (errorDiv) {
                        errorDiv.textContent = validationResult.message;
                        errorDiv.classList.remove('d-none');
                    }
                    return;
                }
                
                var amountValue = parseFloat(amount);
                
                // 禁用按钮
                var submitBtn = document.getElementById('rechargeSubmitBtn');
                submitBtn.disabled = true;
                submitBtn.textContent = '充值中...';
                
                // 发送AJAX请求
                var params = new URLSearchParams();
                params.append('amount', amount);
                
                fetch('${pageContext.request.contextPath}/client/user?action=recharge', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: params.toString()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (successDiv) {
                            successDiv.textContent = data.message;
                            successDiv.classList.remove('d-none');
                        }
                        amountInput.value = '';
                        
                        // 3秒后关闭模态框并刷新页面
                        setTimeout(function() {
                            var modal = bootstrap.Modal.getInstance(document.getElementById('rechargeModal'));
                            if (modal) modal.hide();
                            location.reload();
                        }, 2000);
                    } else {
                        if (errorDiv) {
                            errorDiv.textContent = data.message;
                            errorDiv.classList.remove('d-none');
                        }
                    }
                })
                .catch(error => {
                    if (errorDiv) {
                        errorDiv.textContent = '充值失败，请重试';
                        errorDiv.classList.remove('d-none');
                    }
                })
                .finally(() => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认充值';
                });
            });
        }
        
        // 修改密码功能
        var changePasswordBtn = document.getElementById('changePasswordSubmitBtn');
        if (changePasswordBtn) {
            changePasswordBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                // 重新获取元素和值
                var oldPasswordInput = document.getElementById('oldPassword');
                var newPasswordInput = document.getElementById('newPassword');
                var confirmPasswordInput = document.getElementById('confirmPassword');
                
                if (!oldPasswordInput || !newPasswordInput || !confirmPasswordInput) {
                    console.error('找不到密码输入框');
                    return;
                }
                
                var oldPassword = oldPasswordInput.value;
                var newPassword = newPasswordInput.value;
                var confirmPassword = confirmPasswordInput.value;
                
                if (oldPassword) oldPassword = oldPassword.trim();
                if (newPassword) newPassword = newPassword.trim();
                if (confirmPassword) confirmPassword = confirmPassword.trim();
                
                var errorDiv = document.getElementById('changePasswordError');
                var successDiv = document.getElementById('changePasswordSuccess');
                
                // 清除之前的消息和验证状态
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                oldPasswordInput.classList.remove('is-invalid');
                newPasswordInput.classList.remove('is-invalid');
                confirmPasswordInput.classList.remove('is-invalid');
                
                // 验证输入
                var isValid = true;
                
                if (!oldPassword) {
                    oldPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('oldPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入当前密码';
                    isValid = false;
                }
                
                if (!newPassword) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '请输入新密码';
                    isValid = false;
                } else if (newPassword.length < 6) {
                    newPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('newPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码长度至少6位';
                    isValid = false;
                }
                
                if (!confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '请确认新密码';
                    isValid = false;
                } else if (newPassword !== confirmPassword) {
                    confirmPasswordInput.classList.add('is-invalid');
                    var errorMsg = document.getElementById('confirmPasswordError');
                    if (errorMsg) errorMsg.textContent = '新密码和确认密码不一致';
                    isValid = false;
                }
                
                if (!isValid) {
                    if (errorDiv) {
                        errorDiv.textContent = '请检查输入信息';
                        errorDiv.classList.remove('d-none');
                    }
                    return;
                }
                
                // 禁用按钮
                var submitBtn = document.getElementById('changePasswordSubmitBtn');
                submitBtn.disabled = true;
                submitBtn.textContent = '修改中...';
                
                // 发送AJAX请求
                var params = new URLSearchParams();
                params.append('oldPassword', oldPassword);
                params.append('newPassword', newPassword);
                params.append('confirmPassword', confirmPassword);
                
                fetch('${pageContext.request.contextPath}/client/user?action=changePassword', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: params.toString()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (successDiv) {
                            successDiv.textContent = data.message;
                            successDiv.classList.remove('d-none');
                        }
                        
                        // 清空表单
                        oldPasswordInput.value = '';
                        newPasswordInput.value = '';
                        confirmPasswordInput.value = '';
                        
                        // 3秒后关闭模态框
                        setTimeout(function() {
                            var modal = bootstrap.Modal.getInstance(document.getElementById('changePasswordModal'));
                            if (modal) modal.hide();
                        }, 2000);
                    } else {
                        if (errorDiv) {
                            errorDiv.textContent = data.message;
                            errorDiv.classList.remove('d-none');
                        }
                    }
                })
                .catch(error => {
                    if (errorDiv) {
                        errorDiv.textContent = '修改密码失败，请重试';
                        errorDiv.classList.remove('d-none');
                    }
                })
                .finally(() => {
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认修改';
                });
            });
        }
        
        // 模态框关闭时清除表单和消息
        var rechargeModal = document.getElementById('rechargeModal');
        if (rechargeModal) {
            rechargeModal.addEventListener('hidden.bs.modal', function() {
                var form = document.getElementById('rechargeForm');
                var amountInput = document.getElementById('rechargeAmount');
                var errorDiv = document.getElementById('rechargeError');
                var successDiv = document.getElementById('rechargeSuccess');
                var errorMsg = document.getElementById('rechargeAmountError');
                
                if (form) form.reset();
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                if (amountInput) {
                    amountInput.classList.remove('is-invalid');
                    amountInput.classList.remove('is-valid');
                }
                if (errorMsg) errorMsg.textContent = '';
            });
            
            // 模态框打开时清除之前的校验状态
            rechargeModal.addEventListener('show.bs.modal', function() {
                var amountInput = document.getElementById('rechargeAmount');
                var errorDiv = document.getElementById('rechargeError');
                var successDiv = document.getElementById('rechargeSuccess');
                var errorMsg = document.getElementById('rechargeAmountError');
                
                if (amountInput) {
                    amountInput.value = '';
                    amountInput.classList.remove('is-invalid');
                    amountInput.classList.remove('is-valid');
                }
                if (errorDiv) errorDiv.classList.add('d-none');
                if (successDiv) successDiv.classList.add('d-none');
                if (errorMsg) errorMsg.textContent = '';
            });
        }
        
        var changePasswordModal = document.getElementById('changePasswordModal');
        if (changePasswordModal) {
            changePasswordModal.addEventListener('hidden.bs.modal', function() {
                document.getElementById('changePasswordForm').reset();
                document.getElementById('changePasswordError').classList.add('d-none');
                document.getElementById('changePasswordSuccess').classList.add('d-none');
                document.getElementById('oldPassword').classList.remove('is-invalid');
                document.getElementById('newPassword').classList.remove('is-invalid');
                document.getElementById('confirmPassword').classList.remove('is-invalid');
            });
        }
        
        // 加载购物车数量
        function loadCartCount() {
            <c:if test="${sessionScope.user != null}">
            fetch('${pageContext.request.contextPath}/client/cart?action=count')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const cartCountEl = document.getElementById('cartCount');
                        if (cartCountEl) {
                            cartCountEl.textContent = data.count;
                            if (data.count > 0) {
                                cartCountEl.style.display = 'inline';
                            } else {
                                cartCountEl.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error loading cart count:', error);
                });
            </c:if>
        }
        
        // 页面加载完成后加载购物车数量
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', loadCartCount);
        } else {
            loadCartCount();
        }
        
        // 初始化公告功能
        initAnnouncement();
    }
    
    // 公告功能
    function initAnnouncement() {
        <c:if test="${sessionScope.user != null}">
        var announcementIcon = document.getElementById('announcementIcon');
        var announcementCard = document.getElementById('announcementCard');
        var announcementList = document.getElementById('announcementList');
        var announcementBadge = document.getElementById('announcementBadge');
        var closeBtn = document.getElementById('closeAnnouncementCard');
        var isCardVisible = false;
        var announcementsLoaded = false;
        
        // 页面加载时立即加载公告数量（用于显示角标）
        loadAnnouncementCount();
        
        // 点击图标显示/隐藏卡片
        if (announcementIcon) {
            announcementIcon.addEventListener('click', function(e) {
                e.stopPropagation();
                toggleAnnouncementCard();
            });
        }
        
        // 关闭按钮
        if (closeBtn) {
            closeBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                hideAnnouncementCard();
            });
        }
        
        // 点击外部区域关闭卡片
        document.addEventListener('click', function(e) {
            var container = document.getElementById('announcementContainer');
            if (container && !container.contains(e.target) && isCardVisible) {
                hideAnnouncementCard();
            }
        });
        
        // 鼠标悬浮显示卡片
        if (announcementIcon) {
            announcementIcon.addEventListener('mouseenter', function() {
                if (!isCardVisible) {
                    showAnnouncementCard();
                }
            });
        }
        
        if (announcementCard) {
            announcementCard.addEventListener('mouseleave', function() {
                hideAnnouncementCard();
            });
        }
        
        function toggleAnnouncementCard() {
            if (isCardVisible) {
                hideAnnouncementCard();
            } else {
                showAnnouncementCard();
            }
        }
        
        function showAnnouncementCard() {
            if (announcementCard) {
                announcementCard.style.display = 'block';
                isCardVisible = true;
                
                // 如果还没加载过，加载公告列表
                if (!announcementsLoaded) {
                    loadAnnouncements();
                }
            }
        }
        
        function hideAnnouncementCard() {
            if (announcementCard) {
                announcementCard.style.display = 'none';
                isCardVisible = false;
            }
        }
        
        // 加载公告数量（用于显示角标）
        function loadAnnouncementCount() {
            fetch('${pageContext.request.contextPath}/client/announcement/listAjax')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        // 更新徽章
                        if (announcementBadge) {
                            announcementBadge.textContent = data.data.length;
                            announcementBadge.style.display = 'inline-block';
                        }
                    }
                })
                .catch(error => {
                    console.error('加载公告数量失败:', error);
                });
        }
        
        function loadAnnouncements() {
            if (announcementsLoaded) return;
            
            fetch('${pageContext.request.contextPath}/client/announcement/listAjax')
                .then(response => response.json())
                .then(data => {
                    announcementsLoaded = true;
                    if (data.success && data.data) {
                        displayAnnouncements(data.data);
                        // 更新徽章（如果还没有显示）
                        if (announcementBadge && data.data.length > 0) {
                            announcementBadge.textContent = data.data.length;
                            announcementBadge.style.display = 'inline-block';
                        }
                    } else {
                        displayEmpty();
                    }
                })
                .catch(error => {
                    console.error('加载公告失败:', error);
                    displayEmpty();
                });
        }
        
        function displayAnnouncements(announcements) {
            if (!announcementList) return;
            
            if (announcements.length === 0) {
                displayEmpty();
                return;
            }
            
            var html = '';
            announcements.forEach(function(ann) {
                html += '<div class="announcement-item">';
                html += '<div class="announcement-title">' + escapeHtml(ann.title) + '</div>';
                html += '<div class="announcement-content">' + escapeHtml(ann.content) + '</div>';
                html += '<div class="announcement-time">' + ann.createTime + '</div>';
                html += '</div>';
            });
            
            announcementList.innerHTML = html;
        }
        
        function displayEmpty() {
            if (!announcementList) return;
            announcementList.innerHTML = '<div class="announcement-empty">暂无公告</div>';
        }
        
        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        </c:if>
    }
})();
</script>

<!-- AI咨询悬浮按钮 -->
<a href="${pageContext.request.contextPath}/client/ai/consultation.jsp" class="ai-consultation-float-btn" title="AI农产品咨询">
    <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16">
        <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
        <path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"/>
    </svg>
</a>
